import type { RouteRecordRaw, RouteComponent } from 'vue-router'

// 自动导入所有 index.vue 文件
const modules = import.meta.glob('/src/pages/**/index.vue')

// 将路径转成路由 path + name
function normalizePath(path: string) {
  const routePath = path
    .replace(/^\/src\/pages/, '')
    .replace(/\/index\.vue$/, '')
    .replace(/\[(.+?)\]/g, ':$1') // 支持动态路由
    .replace(/\\/g, '/')

  const fullPath = routePath === '' ? '/' : routePath
  const name =
    fullPath.replace(/^\//, '').replace(/\//g, '-').replace(/\[|\]/g, '') ||
    'home'

  return { fullPath, name }
}

// 平铺路由类型
interface FlatRoute {
  path: string
  name: string
  component: RouteComponent | (() => Promise<{ default: RouteComponent }>)
}

const flatRoutes: FlatRoute[] = []

for (const file in modules) {
  const { fullPath, name } = normalizePath(file)
  flatRoutes.push({
    path: fullPath,
    name,
    component: modules[file] as FlatRoute['component'],
  })
}

// 构建嵌套路由
function buildNestedRoutes(routes: FlatRoute[]): RouteRecordRaw[] {
  const routeMap = new Map<string, RouteRecordRaw>()

  routes.forEach(({ path, name, component }) => {
    if (path === '/') {
      routeMap.set('/', { path: '/', name, component })
      return
    }

    const segments = path.split('/').filter(Boolean)
    let currentPath = ''
    let parent: RouteRecordRaw | undefined

    segments.forEach((segment, index) => {
      currentPath += '/' + segment

      if (!routeMap.has(currentPath)) {
        const newRoute: RouteRecordRaw = {
          path: index === 0 ? '/' + segment : segment,
          children: [],
        }
        routeMap.set(currentPath, newRoute)

        if (parent) {
          parent.children = parent.children || []
          parent.children.push(newRoute)
        }
      }

      if (index === segments.length - 1) {
        const route = routeMap.get(currentPath)!
        route.component = component
        route.name = name
      }

      parent = routeMap.get(currentPath)
    })
  })

  // 找出根路由
  const roots: RouteRecordRaw[] = []
  routeMap.forEach((route) => {
    const isRoot = ![...routeMap.values()].some((r) =>
      r.children?.includes(route),
    )
    if (isRoot) roots.push(route)
  })

  // 确保根路径存在
  if (!roots.find((r) => r.path === '/')) {
    const root = routeMap.get('/')
    if (root) roots.unshift(root)
  }

  return roots
}

const autoRoutes = buildNestedRoutes(flatRoutes)
console.log('🚀 ~ autoRoutes:', autoRoutes)

export default autoRoutes
